package com.example.uupaymuch.controller.channel.wudipay;

import com.example.uupaymuch.controller.notice.wudi.PayComponent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@RestController
public class PayOrderController {

    @Autowired
    private PayComponent payComponent;

    private final Random random = new Random();
    private final double successProbability = 0.5; // 50% 的成功概率

    private static final Map<String, Object> RESPONSE;
    private static final Map<String, Object> PIXCASHIN;

    // 静态初始化块
    static {
        RESPONSE = new HashMap<>();
        RESPONSE.put("external_id", "b1681fe6931c4ff8a57c775d6fee4387");
        RESPONSE.put("payer_request", null);
        RESPONSE.put("additional_information", new Object[]{});
        RESPONSE.put("qr_code", "00020101021226810014br.gov.bcb.pix2559api-h.fakebank.com.br/api/cob/b1681fe6931c4ff8a57c775d6fee43875204000053039865802BR5913SUPERPAGAMENTOS LTDA6009SAO PAULO62070503***630442F4");
        RESPONSE.put("qr_code_image_url", "https://api-h.wudi-pay.codesign.ag/qr_code/WD1727231601932M1724118185RS75L");
        RESPONSE.put("expires_at", "2024-09-25T02:46:09.000000Z");
        RESPONSE.put("provider", "FAKE_BANK");
        RESPONSE.put("provider_account", "1");
        RESPONSE.put("fee", 0.01);
        RESPONSE.put("account_id", 74);
        RESPONSE.put("workspace_id", 34);
        RESPONSE.put("updated_at", "2024-09-25 00:00:00");
        RESPONSE.put("created_at", "2024-09-25 00:00:00");
        RESPONSE.put("id", 130033);
        PIXCASHIN = new HashMap<>();
        PIXCASHIN.put("id", 1);
        PIXCASHIN.put("external_id", "49E665D8EFC646B3B3DB6909E960FB9E");
        PIXCASHIN.put("account_id", 1);
        PIXCASHIN.put("charge_id", 1);
        PIXCASHIN.put("end_to_end_id", "E35624319202312041831InaK8WrSy5b");
        PIXCASHIN.put("amount", 100);
        PIXCASHIN.put("performed_at", "2023-12-04T18:18:27.000000Z");
        PIXCASHIN.put("status", "DONE");
        PIXCASHIN.put("sender_document_number", "00039471697018");
        PIXCASHIN.put("sender_name", "Fulano de TaskLog");
        PIXCASHIN.put("transaction_id", "TX202312031849ZCS4M0LgLIDWP");
        PIXCASHIN.put("initialization_type", "QRDN");
        PIXCASHIN.put("provider", "IUGU");
        PIXCASHIN.put("created_at", "2023-12-04T18:18:34.000000Z");
        PIXCASHIN.put("updated_at", "2023-12-04T18:18:34.000000Z");
    }

    @PostMapping("/api/charges")
    public ResponseEntity<Map<String, Object>> createTransaction(@RequestBody Map<String, Object> request) {
        // 生成一个随机数，并与成功概率进行比较
        boolean isSuccess = random.nextDouble() < successProbability;

        // 模拟入参
        String amount = request.get("amount") != null ? request.get("amount").toString() : "";
        String txid = request.get("txid") != null ? (String) request.get("txid") : "";
        String debtorName = request.get("debtor_name") != null ? (String) request.get("debtor_name") : "";
        String debtorDocumentNumber = request.get("debtor_document_number") != null ? (String) request.get("debtor_document_number") : "";
        String expiration = request.get("expiration") != null ? (String) request.get("expiration") : "300";
        String payStatus = request.get("payStatus") != null ? (String) request.get("payStatus") : "1"; // 正常回调按照成功

        String payStatusStr = "";
        // 使用线程池执行异步操作
        // 构建成功的响应
        Map<String, Object> response = RESPONSE;
        response.put("txid", txid);
        if(StringUtils.isNotEmpty(payStatus)){
            switch (payStatus){
                case "1":
                    payStatusStr = "PAID";
                    break;
                case "2":
                    payStatusStr = "CREATE";
                    break;
                default:
                    payStatusStr = "PAID";
                    break;
            }
        }
//        payStatusStr = isSuccess ? "PAID" : "CREATE";

        response.put("status", "PAID");
        response.put("debtor_document_number", debtorDocumentNumber);
        response.put("debtor_name", debtorName);
        response.put("amount", amount);

        Map<String, Object> pixCashIn = PIXCASHIN;
        response.put("pix_cash_in", pixCashIn);


        // 回调
        payComponent.doNotifyPay(txid, payStatusStr, amount);

        // 立即返回响应（可以选择返回一个临时的响应）
        return ResponseEntity.ok(response);
    }


    @PostMapping("/api/auth")
    public ResponseEntity<Map<String, Object>> authenticate(@RequestBody Map<String, Object> requestBody) {
        String key = requestBody.get("key") != null ? requestBody.get("key").toString() : "";
        String secret = requestBody.get("secret") != null ? (String) requestBody.get("secret") : "";

        Map<String, Object> response = new HashMap<>();
        // 直接返回固定的响应
        response.put("access_token", "123");
        response.put("expires_in", 1800);

        return ResponseEntity.ok(response);
    }

//    @GetMapping("/api/charges/{txid}/simulate_payment")
//    public ResponseEntity<Map<String, Object>> authenticate(@PathVariable String txid) {
//
//        Map<String, Object> response = new HashMap<>();
//        response.put("message", "Payment performed successfully");
//
//        return ResponseEntity.ok(response);
//    }


//    @GetMapping("/api/notify")
//    public void notify(@RequestParam String ifCode,
//                       @RequestParam String wayCode,
//                       @RequestParam String payOrderId,
//                       @RequestParam Integer type) {
//        try {
//            payComponent.notifyPayment(ifCode, wayCode, payOrderId, type, "");
//        } catch (IOException e) {
//        }
//    }
}
